/** 
* @file		timer.c
* @date		November 22, 2012
* @brief	TIM configuration and support functions
* @see		TIM/TIM_ADC_Trigger/main.c
*/

#include "timer.h"


/**
* @brief   		Configure TIM1 and CC4 to generate triggering pulses
* @param  		period		Triggering period in milliseconds
* @retval 		None
*/
void TIM_Config(uint32_t period) {
	RCC_ClocksTypeDef RCC_Clocks;
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	TIM_OCInitTypeDef TIM_OCInitStructure;

	/* Enable clocks for TIM1 */
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
	
	/* TIM1 Configuration */
  TIM_DeInit(TIM1);
  TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
  TIM_OCStructInit(&TIM_OCInitStructure);  
  RCC_GetClocksFreq(&RCC_Clocks);
	
	/* Time base configuration */
  TIM_TimeBaseStructure.TIM_Period = period;
  TIM_TimeBaseStructure.TIM_Prescaler = RCC_Clocks.HCLK_Frequency/1000;       
  TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;    
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  
  TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
  
  /* PWM Mode configuration for Output Compare 4 */
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; /* low edge by default */
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;           
  TIM_OCInitStructure.TIM_Pulse = 0x01;
  TIM_OC4Init(TIM1, &TIM_OCInitStructure);
  
  /* TIM1 enable counter */
  TIM_Cmd(TIM1, ENABLE);
  
  /* Main Output Enable */
  TIM_CtrlPWMOutputs(TIM1, ENABLE);
}


/**
* @brief   		Configure TIM1 and CC4 to generate triggering pulses
* @param  		period		Triggering period in milliseconds
* @retval 		None
*/
void TIM_Stop() {
	TIM_Cmd(TIM1, DISABLE);
	TIM_CtrlPWMOutputs(TIM1, DISABLE);
}
